package com.lxw.framework.exception;

import com.google.common.collect.ImmutableMap;
import com.lxw.framework.model.response.CommonCode;
import com.lxw.framework.model.response.ResponseResult;
import com.lxw.framework.model.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.ConnectException;

/**
 * @AUTHOR: yadong
 * @DATE: 2021/12/28 14:21
 * @DESC:
 */
@ControllerAdvice
@Slf4j
public class CatchException {

    private static ImmutableMap<Class<? extends Throwable>,ResultCode> immutableMap;

    private static ImmutableMap.Builder<Class<? extends Throwable>,ResultCode> builder = ImmutableMap.builder();

    static {
        builder.put(HttpMessageNotReadableException.class,CommonCode.VALIDATA);
        builder.put(ConnectException.class,CommonCode.CONNECTION_DB);
    }

    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseResult catchCustomException(CustomException customException){
        ResultCode resultCode = customException.getResultCode();
        return new ResponseResult(resultCode);
    }

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public ResponseResult catchCustomException(Throwable throwable){

       if(immutableMap ==null){
           //把构建起中的值放入ImmutableMap
           immutableMap = builder.build();
       }
        ResultCode resultCode = immutableMap.get(throwable.getClass());
       if(resultCode != null){
           return new ResponseResult(resultCode);
       }
        log.error(throwable.getMessage());
        return new ResponseResult(CommonCode.SERVER_ERROR);
    }
}
